package org.yty.travelagencymongodb.service.impl;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.yty.travelagencymongodb.model.Entity.Traveller;
import org.yty.travelagencymongodb.repository.TravellerRepository;
import org.yty.travelagencymongodb.service.SignUpService;
import org.yty.travelagencymongodb.service.TourGroupTravellerService;
import org.yty.travelagencymongodb.service.TravellerService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class TravellerServiceImpl implements TravellerService {
    private final TravellerRepository travellerRepository;
    private final MongoTemplate mongoTemplate;
    @Lazy
    @Autowired
    private TourGroupTravellerService tourGroupTravellerService;
    @Lazy
    @Autowired
    private SignUpService signUpService;

    @Override
    public Traveller getById(Long id) {
        Optional<Traveller> option = this.travellerRepository.findById(id);
        if (option.isEmpty()){
            return null;
        }
        return option.get();
    }

    @Override
    public boolean save(Traveller traveller) {
        if (traveller.getId() == null){
            traveller.setId(IdUtil.getSnowflakeNextId());
        }
        traveller.setCreateTime(LocalDateTime.now());
        traveller.setUpdateTime(LocalDateTime.now());
        traveller = this.travellerRepository.insert(traveller);
        if (traveller != null){
            return true;
        }
        return false;
    }

    @Override
    public boolean update(Traveller traveller) {
        traveller.setUpdateTime(LocalDateTime.now());
        traveller = this.travellerRepository.save(traveller);
        return traveller != null;
    }

    @Override
    public void removeById(Long id) {
        this.tourGroupTravellerService.deleteByTravellerId(id);
        this.signUpService.deleteByTravellerId(id);
        this.travellerRepository.deleteById(id);
    }

    @Override
    public List<Traveller> getListByIdList(List<Long> travellerIdList) {
        Criteria queryCriteria = Criteria.where("id").in(travellerIdList);
        return this.mongoTemplate.find(new Query(queryCriteria),Traveller.class);
    }
}
